package io.aicn.lowcode.mapper.dbmanager;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import io.aicn.lowcode.entity.dbmanager.DataDictionary;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 数据字典Mapper接口
 * 
 * @author lowcode-generator
 * @since 2025-01-25
 */
@Mapper
public interface DataDictionaryMapper extends BaseMapper<DataDictionary> {

    /**
     * 根据字典类型查询字典项
     * 
     * @param dictType 字典类型
     * @return 字典项列表
     */
    @Select("SELECT * FROM dbm_data_dictionary WHERE dict_type = #{dictType} AND is_enabled = 1 ORDER BY sort_order, dict_code")
    List<DataDictionary> selectByDictType(@Param("dictType") String dictType);

    /**
     * 根据字典类型和编码查询字典项
     * 
     * @param dictType 字典类型
     * @param dictCode 字典编码
     * @return 字典项
     */
    @Select("SELECT * FROM dbm_data_dictionary WHERE dict_type = #{dictType} AND dict_code = #{dictCode}")
    DataDictionary selectByTypeAndCode(@Param("dictType") String dictType, @Param("dictCode") String dictCode);

    /**
     * 根据字典类型和值查询字典项
     * 
     * @param dictType 字典类型
     * @param dictValue 字典值
     * @return 字典项
     */
    @Select("SELECT * FROM dbm_data_dictionary WHERE dict_type = #{dictType} AND dict_value = #{dictValue}")
    DataDictionary selectByTypeAndValue(@Param("dictType") String dictType, @Param("dictValue") String dictValue);

    /**
     * 查询所有字典类型
     * 
     * @return 字典类型列表
     */
    @Select("SELECT DISTINCT dict_type FROM dbm_data_dictionary ORDER BY dict_type")
    List<String> selectAllDictTypes();

    /**
     * 检查字典编码是否存在
     * 
     * @param dictType 字典类型
     * @param dictCode 字典编码
     * @param excludeId 排除的ID（用于更新时检查）
     * @return 数量
     */
    @Select("SELECT COUNT(*) FROM dbm_data_dictionary WHERE dict_type = #{dictType} AND dict_code = #{dictCode} AND id != #{excludeId}")
    int countByTypeAndCodeExcludeId(@Param("dictType") String dictType, @Param("dictCode") String dictCode, @Param("excludeId") Long excludeId);

    /**
     * 获取字典类型下的最大排序号
     * 
     * @param dictType 字典类型
     * @return 最大排序号
     */
    @Select("SELECT COALESCE(MAX(sort_order), 0) FROM dbm_data_dictionary WHERE dict_type = #{dictType}")
    Integer getMaxSortOrderByType(@Param("dictType") String dictType);
}